package com.hbpu.schedule.controller;

import com.hbpu.schedule.common.Result;
import com.hbpu.schedule.common.ResultCodeEnum;
import com.hbpu.schedule.pojo.SysUser;
import com.hbpu.schedule.service.SysUserService;
import com.hbpu.schedule.service.impl.SysUserServiceImpl;
import com.hbpu.schedule.util.MD5Util;
import com.hbpu.schedule.util.WebUtil;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebServlet("/user/*")
public class SysUserController extends BaseController {
    private SysUserService sysUserService = new SysUserServiceImpl();

    protected void regist(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        String userPwd = request.getParameter("userPwd");

        SysUser sysUser = new SysUser(null, username, userPwd);

        int result = sysUserService.addUser(sysUser);

        if (result == 1) {
            response.sendRedirect("/registSuccess.html");
        } else {
            response.sendRedirect("/registFail.html");
        }
    }

    protected void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("userPwd");

        SysUser sysUser = sysUserService.userSelectByName(username);
        if (sysUser == null) {
            response.sendRedirect("/loginUsernameError.html");
        } else if (!MD5Util.encrypt(password).equals(sysUser.getUserPwd())) {
            response.sendRedirect("/loginPasswordError.html");
        } else {
            HttpSession session = request.getSession();
            session.setAttribute("user", sysUser);
            response.sendRedirect("/showSchedule.html");
        }
    }

    protected void checkUserUsed(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        SysUser sysUser = sysUserService.userSelectByName(username);

        Result<Object> ok = Result.ok(null);

        if (sysUser != null) {
            ok = Result.build(null, ResultCodeEnum.USERNAME_USED);
        }

        WebUtil.writeJson(response, ok);
    }
}
